﻿using AutoMapper;
using B.S.AuthCenter.Api.Read.Application.Command.Roles;
using B.S.AuthCenter.Api.Read.DTOs;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Read.Application.Handler.Roles
{
    public class GetUserRoleHandler : IRequestHandler<GetUserRoleCommand, ApiResult<List<URDTO>>>
    {
        IBaseRepository<UserModel> userRepo;
        IBaseRepository<UserRoleModel> UrRepo;
        IMapper mapper;

        public GetUserRoleHandler(IBaseRepository<UserModel> userRepo, IBaseRepository<UserRoleModel> urRepo, IMapper mapper)
        {
            this.userRepo = userRepo;
            this.UrRepo = urRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<URDTO>>> Handle(GetUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<URDTO>> res=new ApiResult<List<URDTO>>();
            var list=UrRepo.GetAll().Where(x=>x.Rid==request.Rid && !x.IsDeleted);
            var model=mapper.Map<List<URDTO>>(list);
            foreach (var item in model)
            {
                  
                    item.UserName = userRepo.GetAll().FirstOrDefault(x => x.Id == item.Uid).UserName;
                    item.DepartmentId = userRepo.GetAll().FirstOrDefault(x => x.Id == item.Uid).DepartmentId;
            }
            res.Msg = "查询角色分配用户成功";
            res.Code = ApiEnum.Success;
            res.Datas = model;
            return Task.FromResult(res);
        }
    }
}
